package db

import (
	"common_backend/common/config"
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var Db *gorm.DB

func SetupDBLink() error {
	var err error
	var dbconfig = config.Config.Db

	url := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		dbconfig.User,
		dbconfig.Password,
		dbconfig.Host,
		dbconfig.Port,
		dbconfig.Db,
		dbconfig.Charset)

	Db, err = gorm.Open(mysql.Open(url), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(err)
	}
	if Db.Error != nil {
		panic(Db.Error)
	}
	sqlDB, err := Db.DB()
	sqlDB.SetMaxIdleConns(dbconfig.MaxIdle)
	sqlDB.SetMaxOpenConns(dbconfig.MaxOpen)
	return nil
}
